package system

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"go-admin/app/admin/models"
	"go-admin/tools"
	"go-admin/tools/app"
	"net/url"
	"strconv"
	"strings"
)

/**
* @Description:
* @Author: yuweizhu
* @Date: 2020/11/15 12:16 下午
**/
// TODO 境外域名判断
func CreateShortUrl(c *gin.Context) {
	var data models.TShortUrl
	var account models.TAccount
	var permConfig models.TRightsPermConfig
	var tmpData models.TShortUrl
	err := c.BindWith(&data, binding.JSON)
	tools.HasError(err, "非法数据格式", 500)
	if parseUrl(&data.LongUrl) != "" {
		tools.HasError(errors.New("url不合法，需要以http/https开头"), "链接无效，请重新输入", 500)
	}
	if value := c.Param("id"); value != "" {
		data.Uuid = value
		permConfig.Type = 1
	} else {
		res, _ := strconv.Atoi(data.UserId)
		if res == 0 {
			tools.HasError(errors.New("用户不存在"), "用户不存在", 500)
		}
		account.UserId = int64(res)
		resultAccount, err := account.Get()
		tools.HasError(err, "用户不存在", 500)
		if resultAccount.SumAmount == 0 {
			permConfig.Type = 2
		} else if resultAccount.SumAmount < 500 {
			permConfig.Type = 3
		} else if resultAccount.Amount < 1000 {
			permConfig.Type = 4
		} else if resultAccount.Amount < 2000 {
			permConfig.Type = 5
		} else {
			permConfig.Type = 6
		}
	}
	// 获取链接数量
	if data.UserId == "" {
		tmpData.UserId = data.Uuid
	} else {
		tmpData.UserId = data.UserId
	}
	count, _ := tmpData.Count()
	p, _ := permConfig.Get()
	if p.LinkCount != -1 && int(count) >= p.LinkCount {
		tools.HasError(errors.New("您的流量余额不足，请联系客服充值"), "您的流量余额不足，请联系客服充值", 500)
	}

	data.Type = p.Type
	data.ClickLimit = p.ClickCount
	_, err = data.Insert()
	tools.HasError(err, "添加失败", 500)
	app.OK(c, []models.TShortUrl{data}, "添加成功")
}

func QueryShortUrl(c *gin.Context) {
	var data models.SysUser
	var id int
	var err error

	if value := c.Param("id"); value != "" {
		id, err = tools.StringToInt(value)
	}
	data.UserId = id
	result, err := data.Get()
	tools.HasError(err, "", -1)
	app.OK(c, result, "")
}

func ModifyShortUrl(c *gin.Context) {
	var data models.TShortUrl
	err := c.BindWith(&data, binding.JSON)
	tools.HasError(err, "非法数据格式", 500)

	err = data.Update(data.ID)
	tools.HasError(err, "修改失败", 500)
	app.OK(c, data.ID, "修改成功")
}

func DeleteShortUrl(c *gin.Context)  {
	var data models.TShortUrl
	err := c.BindWith(&data, binding.JSON)
	tools.HasError(err, "", -1)
	data.Status = "0"
	err = data.Update(data.ID)
	tools.HasError(err, "删除失败", 500)
	app.OK(c, data.ID, "删除成功")
}

func GetUrlList(c *gin.Context) {
	var data models.TShortUrl
	var err error
	var pageSize = 10
	var pageIndex = 1

	size := c.Request.FormValue("pageSize")
	if size != "" {
		pageSize, err = tools.StringToInt(size)
	}

	index := c.Request.FormValue("pageIndex")
	if index != "" {
		pageIndex, err = tools.StringToInt(index)
	}
	userId := c.Request.FormValue("userId")

	data.UserName = c.Request.FormValue("username")
	data.LongUrl = c.Request.FormValue("longUrl")
	data.UserId = userId
	//data.Status = "1"

	result, count, err := data.GetPage(pageSize, pageIndex)
	tools.HasError(err, "", -1)

	app.PageOK(c, result, count, pageIndex, pageSize, "")
}

func parseUrl(longUrl *string) string{
	var longURL *url.URL
	longURL, err := url.Parse(*longUrl)
	if err != nil {
		return "链接不合法"
	} else {
		// TODO 判断系统内置短域名host
		//if longURL.Host == ""{
		//	w.WriteHeader(http.StatusBadRequest)
		//	errMsg, _ := json.Marshal(errorResp{Msg: "requested url is already shortened"})
		//	return
		//}
		if strings.ToLower(longURL.Scheme) != "http" && strings.ToLower(longURL.Scheme) != "https" {
			*longUrl = "http://" + *longUrl
		}
	}
	return ""
}